#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

import logging
logger = logging.getLogger(__name__)

from email.utils import formatdate
import requests, json, time, datetime
import auth, sendEmailClass
from grafanaCallBack.conf import setting

emallHost = setting.configs[u'emallHost']
emallUser = setting.configs[u'emallUser']
emallPasswd = setting.configs[u'emallPasswd']

def callBack(packageAbsLogPath, repoName, subject, toList, ccList):
    accessKey = 'No3OcQaeozJWKUISUAqgRKnpXFUAUOezBZNr3FbO'
    secretKey = 'kY-sGTTMQY7yoPii2zvebph9JRVb5DPH81RC2CKU'

    endPoint = 'https://nb-insight.qiniuapi.com'
    #RepoName = 'nginx_access_log'
    resource = '/v5/repos/'+repoName+'/search'

    authorizationObj = auth.Auth(accessKey, secretKey)
    authorization = authorizationObj.sign_request('POST',resource)

    url = endPoint + '/v5/repos/' + repoName + '/search'
    nowTime = datetime.datetime.now()
    startTime = datetime.datetime.strftime(nowTime -  datetime.timedelta(minutes=5),'%Y-%m-%dT%H:%M:%S.00+08:00')
    endTime = datetime.datetime.strftime(nowTime,'%Y-%m-%dT%H:%M:%S.00+08:00')
    logger.info('开始时间:'+str(startTime)+'结束时间:'+str(endTime))

    headers = {'Content-Type':'application/json',
               'Date':formatdate(None, usegmt=True),
               'resource':resource,
               'qiniu-headers':'',
               'Authorization':'Pandora '+authorization}

    if repoName == 'nginx_access_log':
        logger.info('Nginx Access 异常日志报警………………')
        # packageAbsLogPath = '/APP/web/logs/nginx_log/my.yunlai.cn/my.yunlai.cn.log'
        # queryString = 'datasource:"/APP/web/logs/nginx_log/boss.yunlai.cn/boss.yunlai.cn.log" AND time_local:[2018-11-06T00:00:00.00+08:00 TO 2018-11-06T23:59:59.59+08:00]'
        queryString = 'datasource:"%s" AND time_local:[%s TO %s] AND status:>=400' % (packageAbsLogPath, startTime, endTime)
        logger.info('查询语句为:'+str(queryString))
        searchCondition = {
           "size":500,
           "query":queryString,
           # "scroll":"3m",
           "sort":"time_local:desc",
           "from":1,
           # "fields":"<status>,",
           "highlight":{
              "pre_tags":[
                 "<tag1>"
              ],
              "post_tags":[
                 "</tag1>"
              ],
              "fields":{
                 "<高亮的字段>":{}
              },
              "require_field_match":False,
              "fragment_size":100
           }
        }
        result = requests.post(url, headers=headers, data=json.dumps(searchCondition))
        print result.status_code
        resultObj = json.loads(result.text)
        for k,v in resultObj.items():
            print k,'===>',v
        print len(resultObj['data'])
        content = '<h3>最近5分钟一共产生<span style="color:red">%s</span>条错误日志<h3><h3 style="margin-bottom: 0px">错误日志明细：</h3><ul>' % resultObj['total']
        for row in resultObj['data']:
            lineLog = r'<li style="list-style: none; border-bottom: #ccc 1px dotted;">'\
                      '%s %s '\
                      '%s %s %s '\
                      '%s <span style="color:red;">%s</span> <span style="color:red;">%s</span> '\
                      '%s <span style="color:red;">%s</span> %s '\
                      '%s %s %s '\
                      '%s %s '\
                      '</li>' % (
                str(datetime.datetime.strptime(row.get('time_local', '-')[0:19],'%Y-%m-%dT%H:%M:%S') + datetime.timedelta(hours=8)), row.get('client_ip', '-'), \
                row.get('client_ip_Country', '-'), row.get('client_ip_Region', '-'), row.get('client_ip_City', '-'), \
                row.get('request_method', '-'), row.get('uri'), row.get('args', '-'), \
                row.get('server_protocol', '-'), row.get('status'), row.get('body_bytes_sent', '-'), \
                row.get('http_referer', '-'), row.get('http_user_agent'), row.get('request_time','-'), \
                row.get('request_length', '-'), row.get('upstream_response_time', '-'),
            )
            logger.info(str(lineLog))
            content = content + lineLog
        content = content + '</ul><h5>注：只显示最近5分钟内前500条错误日志</h5>'
        print content
    elif repoName == 'application_log':
        logger.info('应用错误日志报警………………')
        # packageAbsLogPath = '/APP/web/logs/nginx_log/my.yunlai.cn/my.yunlai.cn.log'
        # queryString = 'datasource:"/APP/web/logs/nginx_log/boss.yunlai.cn/boss.yunlai.cn.log" AND time_local:[2018-11-06T00:00:00.00+08:00 TO 2018-11-06T23:59:59.59+08:00]'
        queryString = 'datasource:"%s" AND time_local:[%s TO %s] AND loglevel:ERROR' % (packageAbsLogPath, startTime, endTime)
        logger.info('查询语句为:'+str(queryString))
        searchCondition = {
            "size": 500,
            "query": queryString,
            # "scroll":"3m",
            "sort": "time_local:desc",
            "from": 1,
            # "fields":"<status>,",
            "highlight": {
                "pre_tags": [
                    "<tag1>"
                ],
                "post_tags": [
                    "</tag1>"
                ],
                "fields": {
                    "<高亮的字段>": {}
                },
                "require_field_match": False,
                "fragment_size": 100
            }
        }
        result = requests.post(url, headers=headers, data=json.dumps(searchCondition))
        print result.status_code
        resultObj = json.loads(result.text)
        for k, v in resultObj.items():
            logger.info(str(k) + '===>' + str(v))
        print len(resultObj['data'])
        content = '<h3>最近5分钟一共产生<span style="color:red">%s</span>条错误日志<h3><h3 style="margin-bottom: 0px">错误日志明细：</h3><ul>' % resultObj['total']
        for row in resultObj['data']:
            lineLog = r'<li style="list-style: none; border-bottom: #ccc 1px dotted;">' \
                      '%s %s ' \
                      '<span style="color: red;">%s</span> %s %s ' \
                      '</li>' % (
                str(datetime.datetime.strptime(row.get('time_local', '-')[0:19], '%Y-%m-%dT%H:%M:%S') + datetime.timedelta(hours=8)), row.get('thread', '-'), \
                row.get('loglevel', '-'), row.get('message', '-'), row.get('localip', '-')
                )
            logger.info(str(lineLog))
            content = content + lineLog
        content = content + '</ul><h5>注：只显示最近5分钟内前500条错误日志</h5>'
        logger.info(str(content))
    else:
        content = '传入的日志库不对，无法从七牛云日志库中查询日志，请检查！'

    # toList = ["2368691083@qq.com, 986526367@qq.com"]    #定义邮件收件人
    # ccList = ["mason@yunlai.cn, magicjms@sina.com"]     #定义邮件抄送人
    # subject = u"grafan回调测试--%s" % datetime.datetime.now()      #定义邮件主题

    sendEmallObj = sendEmailClass.sendEmallClass(emallHost, emallUser, emallPasswd)
    sendEmallObj.doSendEmall(toList, ccList, subject=subject, content=content)

if __name__ == '__main__':
    packageAbsLogPath = '/APP/web/logs/nginx_log/my.yunlai.cn/my.yunlai.cn.log'
    repoName = 'nginx_access_log'
    callBack(packageAbsLogPath,repoName)
    packageAbsLogPath.endswith()

    packageAbsLogPath = '/APP/web/logs/cjds-user-service/log.log'
    repoName = 'applicationlog'
    callBack(packageAbsLogPath, repoName)





